package com.yuang.zookeeper;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;

import java.util.List;

public class App 
{
    static String  CONNECTION_STRING = "127.0.0.1:2181";
    static ZkClient zk;
    static {
        zk = new ZkClient(CONNECTION_STRING,5000);
        if(zk!=null) {
            System.out.println("connecte success");
        }
    }

    private void createNode() {
        String res0 = zk.create("/node0","123", CreateMode.PERSISTENT);
        System.out.println("create node:"+res0);

    }

    private void createChild() {
        zk.createEphemeral("/node0/node1","123");
    }

    private void readNode() {
        System.out.println("read node data:"+zk.readData("/node0/node1"));
    }

    private void getChildren() {
        List<String> list = zk.getChildren("/");
        System.out.println("get children:"+list);
    }

    private void editNode() {
        zk.writeData("/node0","456");
        System.out.println("after edit node");
        this.readNode();
    }

    private void deleteNode() {
        // 递归删除节点
        zk.deleteRecursive("/node0");
        System.out.println("delete all nodes recurisvely");
    }


    public static void main(String[] args) {
        App app = new App();
        // listen can be subscribed even the node still haven't been created.
        zk.subscribeChildChanges("/node0", new IZkChildListener() {
            public void handleChildChange(String s, List<String> list) throws Exception {
                System.out.println("node changed");
            }
        });

        zk.subscribeDataChanges("/node0", new IZkDataListener() {
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println("data change");
            }

            public void handleDataDeleted(String s) throws Exception {

            }
        });
        app.createNode();
        app.createChild(); //trigger subscribeChildChanges listenner
        app.getChildren();
        app.readNode();
        app.editNode(); // trigger subscribeDataChanges listenner
        app.deleteNode(); // trigger subscribeChildChanges listener
        app.getChildren();
    }
}
